import React, {
  useEffect,useState
} from 'react'
// 引入 ECharts 主模块
import echarts from 'echarts/lib/echarts';
// 引入折线图
import 'echarts/lib/chart/line';
import 'echarts/lib/component/dataZoom';

export function useChart(chartRef, option) {
  const [echartsInstance, setEchartsInstance] = useState()

  function initChart() {
    if (chartRef.current) {
      setEchartsInstance(echarts.init(chartRef.current))
    } 
  }
  //监听依赖变化，并根据需要更新图表数据
  useEffect(() => {
      echartsInstance && echartsInstance.setOption(option)
      console.log('echartsInstance-更新',echartsInstance)
  }, [echartsInstance, option])
  // 仅第一次挂载时执行
  useEffect(() => {
    initChart()
    return () => {
        echartsInstance && echartsInstance.dispose()
        console.log('echart-卸载了')
    }
  }, [])
}
